package cn.wrl.config;

import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.cloud.gateway.filter.ratelimit.RedisRateLimiter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import reactor.core.publisher.Mono;

/**
 * redis限流器
 */
@Configuration
public class RedisLimiterConfiguration {

    //ID : KEY

    /**
     * 通过用户访问的url最后的地址，作为redis的key
     */
    @Bean
    @Primary    //唯一KeyResolver，调用这个key时，使用
    public KeyResolver remoteAddrKeyResolver() {
        return exchange ->
                Mono.just(exchange.getRequest()
                        .getRemoteAddress()
                        .getAddress()
                        .getHostAddress());

    }

    @Bean("redisLimiterUser")
    @Primary
    public RedisRateLimiter redisLimiterUser() {
        //限流桶的速率；桶的容量
        return new RedisRateLimiter(10, 20);
    }

    @Bean("redisLimiterItem")
//    @Primary
    public RedisRateLimiter redisLimiterItem() {
        return new RedisRateLimiter(50, 100);
    }

//    @Bean("redisLimiterUser")
//    @Primary
//    public RedisRateLimiter redisLimiterUser() {
//        //限流桶的速率；桶的容量
//        return new RedisRateLimiter(10, 20);
//    }

}
